﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.Composition;
using UnfriendlyFire.Models;

namespace UnfriendlyFire.Controllers
{
    [Export(typeof(IController))]
    [ExportMetadata("Name", "Scenario")]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class ScenarioController : Controller
    {
        private GameRepository _gameRepository;

        [ImportingConstructor]
        public ScenarioController(GameRepository gameRepository)
        {
            _gameRepository = gameRepository;
        }

        public ActionResult Index()
        {
            return View(_gameRepository.AuthoredScenarios);
        }

        public ActionResult Details(int id)
        {
            return View();
        }

        public ActionResult Create()
        {
            return View(Scenario.CreateScenario(0, null, "Scenario Name", "Scenarion Description", 0, "/Content/Images/DefaultScenarioIcon.png"));
        }

        [HttpPost]
        [Authorize]
        public ActionResult Create([ModelBinder(typeof(ScenarioModelBinder))] Scenario scenario)
        {
            if (!ModelState.IsValid)
            {
                return View(scenario);
            }
            try
            {
                scenario.Author = _gameRepository.Officers.First(o => o.Email == HttpContext.User.Identity.Name);
                _gameRepository.Scenarios.AddObject(scenario);
                _gameRepository.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                ModelState.AddModelError(string.Empty, e);
                return View(scenario);
            }
        }

        public ActionResult Edit(int id)
        {
            return View();
        }

        [HttpPost]
        [Authorize]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            return View();
        }

        [HttpPost]
        [Authorize]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
